package ltd.newbee.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ltd.newbee.mall.api.mall.param.SaveCartItemParam;
import ltd.newbee.mall.api.mall.param.UpdateCartItemParam;
import ltd.newbee.mall.api.mall.vo.NewBeeMallShoppingCartItemVO;
import ltd.newbee.mall.common.Constants;
import ltd.newbee.mall.common.NewBeeMallException;
import ltd.newbee.mall.common.ServiceResultEnum;
import ltd.newbee.mall.entity.*;
import ltd.newbee.mall.mapper.NewBeeMallGoodsMapper;
import ltd.newbee.mall.mapper.NewBeeMallShoppingCartItemMapper;
import ltd.newbee.mall.service.NewBeeMallShoppingCartService;
import ltd.newbee.mall.util.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class NewBeeMallShoppingCartServiceImpl implements NewBeeMallShoppingCartService {
    @Autowired
    private NewBeeMallShoppingCartItemMapper newBeeMallShoppingCartItemMapper;

    @Autowired
    private NewBeeMallGoodsMapper newBeeMallGoodsMapper;

    @Override
    public PageResult getMyShoppingCartItems(PageQuery pageQuery) {
        Long userId = (Long) pageQuery.get("userId");
        Page<NewBeeMallShoppingCartItem> page = new Page<>(pageQuery.getPageIndex(), pageQuery.getPageSize());
        LambdaQueryWrapper<NewBeeMallShoppingCartItem> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper
                .eq(NewBeeMallShoppingCartItem::getUserId, userId)
                .eq(NewBeeMallShoppingCartItem::getIsDeleted, 0);

        IPage<NewBeeMallShoppingCartItem> pageData = newBeeMallShoppingCartItemMapper.selectPage(page, queryWrapper);
        return new PageResult<NewBeeMallShoppingCartItemVO>(getNewBeeMallShoppingCartItemVOS(pageData.getRecords()), (int) pageData.getTotal(), (int) pageData.getSize(), (int) pageData.getCurrent());
    }

    @Override
    public List<NewBeeMallShoppingCartItemVO> getMyShoppingCartItems(Long userId) {
        LambdaQueryWrapper<NewBeeMallShoppingCartItem> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper
                .eq(NewBeeMallShoppingCartItem::getUserId, userId)
                .eq(NewBeeMallShoppingCartItem::getIsDeleted, 0);
        List<NewBeeMallShoppingCartItem> newBeeMallShoppingCartItems = newBeeMallShoppingCartItemMapper.selectList(queryWrapper);
        return getNewBeeMallShoppingCartItemVOS(newBeeMallShoppingCartItems);
    }

    @Override
    public String saveNewBeeMallCartItem(SaveCartItemParam saveCartItemParam, Long userId) {
        LambdaQueryWrapper<NewBeeMallShoppingCartItem> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper
                .eq(NewBeeMallShoppingCartItem::getUserId, userId)
                .eq(NewBeeMallShoppingCartItem::getGoodsId, saveCartItemParam.getGoodsId())
                .eq(NewBeeMallShoppingCartItem::getIsDeleted, 0);
        NewBeeMallShoppingCartItem temp = newBeeMallShoppingCartItemMapper.selectOne(queryWrapper);
        //已存在
        if (temp != null) {
            NewBeeMallException.fail(ServiceResultEnum.SHOPPING_CART_ITEM_EXIST_ERROR.getResult());
        }

        LambdaQueryWrapper<NewBeeMallGoods> goodQueryWrapper = Wrappers.lambdaQuery();
        goodQueryWrapper.eq(NewBeeMallGoods::getGoodsId, saveCartItemParam.getGoodsId());
        NewBeeMallGoods newBeeMallGoods = newBeeMallGoodsMapper.selectOne(goodQueryWrapper);

        queryWrapper.clear();
        queryWrapper
                .eq(NewBeeMallShoppingCartItem::getUserId, userId)
                .eq(NewBeeMallShoppingCartItem::getIsDeleted, 0);
        //商品为空
        if (newBeeMallGoods == null) {
            return ServiceResultEnum.GOODS_NOT_EXIST.getResult();
        }
        Long totalItem = newBeeMallShoppingCartItemMapper.selectCount(queryWrapper);
        //添加的商品如果数量小于1
        if (saveCartItemParam.getGoodsCount() < 1) {
            return ServiceResultEnum.SHOPPING_CART_ITEM_NUMBER_ERROR.getResult();
        }
        //超出单个商品的最大数量
        if (saveCartItemParam.getGoodsCount() > Constants.SHOPPING_CART_ITEM_LIMIT_NUMBER) {
            return ServiceResultEnum.SHOPPING_CART_ITEM_LIMIT_NUMBER_ERROR.getResult();
        }
        // 超出最大数量
        if (totalItem > Constants.SHOPPING_CART_ITEM_TOTAL_NUMBER) {
            return ServiceResultEnum.SHOPPING_CART_ITEM_TOTAL_NUMBER_ERROR.getResult();
        }
        NewBeeMallShoppingCartItem newBeeMallShoppingCartItem = new NewBeeMallShoppingCartItem();
        BeanUtil.copyProperties(saveCartItemParam, newBeeMallShoppingCartItem);
        newBeeMallShoppingCartItem.setUserId(userId);
        // 保存记录
        if (newBeeMallShoppingCartItemMapper.insert(newBeeMallShoppingCartItem) > 0) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }

    @Override
    public String updateNewBeeMallCartItem(UpdateCartItemParam updateCartItemParam, Long userId) {
        LambdaQueryWrapper<NewBeeMallShoppingCartItem> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper
                .eq(NewBeeMallShoppingCartItem::getCartItemId, updateCartItemParam.getCartItemId())
                .eq(NewBeeMallShoppingCartItem::getUserId, userId)
                .eq(NewBeeMallShoppingCartItem::getIsDeleted, 0);
        NewBeeMallShoppingCartItem newBeeMallShoppingCartItemUpdate = newBeeMallShoppingCartItemMapper.selectOne(queryWrapper);
        // 商品不存在
        if (newBeeMallShoppingCartItemUpdate == null) {
            return ServiceResultEnum.DATA_NOT_EXIST.getResult();
        }
        //超出单个商品的最大数量
        if (updateCartItemParam.getGoodsCount() > Constants.SHOPPING_CART_ITEM_LIMIT_NUMBER) {
            return ServiceResultEnum.SHOPPING_CART_ITEM_LIMIT_NUMBER_ERROR.getResult();
        }
        //数值相同，则不执行数据操作
        if (updateCartItemParam.getGoodsCount().equals(newBeeMallShoppingCartItemUpdate.getGoodsCount())) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        newBeeMallShoppingCartItemUpdate.setGoodsCount(updateCartItemParam.getGoodsCount());
        newBeeMallShoppingCartItemUpdate.setUpdateTime(new Date());
        //修改记录
        if (newBeeMallShoppingCartItemMapper.update(newBeeMallShoppingCartItemUpdate, queryWrapper) > 0) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }

    @Override
    public NewBeeMallShoppingCartItem getNewBeeMallCartItemById(Long newBeeMallShoppingCartItemId) {
        LambdaQueryWrapper<NewBeeMallShoppingCartItem> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper
                .eq(NewBeeMallShoppingCartItem::getCartItemId, newBeeMallShoppingCartItemId)
                .eq(NewBeeMallShoppingCartItem::getIsDeleted, 0);
        NewBeeMallShoppingCartItem newBeeMallShoppingCartItem = newBeeMallShoppingCartItemMapper.selectOne(queryWrapper);
        if (newBeeMallShoppingCartItem == null) {
            NewBeeMallException.fail(ServiceResultEnum.DATA_NOT_EXIST.getResult());
        }
        return newBeeMallShoppingCartItem;
    }

    @Override
    public Boolean deleteById(Long shoppingCartItemId, Long userId) {
        LambdaQueryWrapper<NewBeeMallShoppingCartItem> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper
                .eq(NewBeeMallShoppingCartItem::getCartItemId, shoppingCartItemId)
                .eq(NewBeeMallShoppingCartItem::getUserId, userId)
                .eq(NewBeeMallShoppingCartItem::getIsDeleted, 0);
        NewBeeMallShoppingCartItem newBeeMallShoppingCartItem = newBeeMallShoppingCartItemMapper.selectOne(queryWrapper);
        if (newBeeMallShoppingCartItem == null) {
            return false;
        }
        LambdaUpdateWrapper<NewBeeMallShoppingCartItem> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper
                .set(NewBeeMallShoppingCartItem::getIsDeleted, 1)
                .eq(NewBeeMallShoppingCartItem::getCartItemId, shoppingCartItemId)
                .eq(NewBeeMallShoppingCartItem::getIsDeleted, 0);
        return newBeeMallShoppingCartItemMapper.update(null, updateWrapper) > 0;
    }

    @Override
    public int deleteByIds(List<Long> shoppingCartItemId, Long userId) {
        LambdaUpdateWrapper<NewBeeMallShoppingCartItem> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper
                .set(NewBeeMallShoppingCartItem::getIsDeleted, 1)
                .in(NewBeeMallShoppingCartItem::getCartItemId, shoppingCartItemId)
                .eq(NewBeeMallShoppingCartItem::getUserId, userId);
        return newBeeMallShoppingCartItemMapper.update(null, updateWrapper);
    }

    /**
     * 数据转换
     *
     * @param newBeeMallShoppingCartItems
     * @return
     */
    private List<NewBeeMallShoppingCartItemVO> getNewBeeMallShoppingCartItemVOS(List<NewBeeMallShoppingCartItem> newBeeMallShoppingCartItems) {
        List<NewBeeMallShoppingCartItemVO> newBeeMallShoppingCartItemVOS = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(newBeeMallShoppingCartItems)) {
            List<Long> goodsIds = newBeeMallShoppingCartItems.stream().map(NewBeeMallShoppingCartItem::getGoodsId).collect(Collectors.toList());
            LambdaQueryWrapper<NewBeeMallGoods> goodQueryWrapper = Wrappers.lambdaQuery();
            goodQueryWrapper.in(NewBeeMallGoods::getGoodsId, goodsIds).last("ORDER BY FIELD(goods_id, " + goodsIds.stream().map(String::valueOf).collect(Collectors.joining(",")) + ")");
            List<NewBeeMallGoods> newBeeMallGoods = newBeeMallGoodsMapper.selectList(goodQueryWrapper);
            Map<Long, NewBeeMallGoods> newBeeMallGoodsMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(newBeeMallGoods)) {
                newBeeMallGoodsMap = newBeeMallGoods.stream().collect(Collectors.toMap(NewBeeMallGoods::getGoodsId, item -> item));
            }
            for (NewBeeMallShoppingCartItem newBeeMallShoppingCartItem : newBeeMallShoppingCartItems) {
                NewBeeMallShoppingCartItemVO newBeeMallShoppingCartItemVO = new NewBeeMallShoppingCartItemVO();
                BeanUtil.copyProperties(newBeeMallShoppingCartItem, newBeeMallShoppingCartItemVO);
                if (newBeeMallGoodsMap.containsKey(newBeeMallShoppingCartItem.getGoodsId())) {
                    NewBeeMallGoods newBeeMallGoodsTemp = newBeeMallGoodsMap.get(newBeeMallShoppingCartItem.getGoodsId());
                    newBeeMallShoppingCartItemVO.setGoodsCoverImg(newBeeMallGoodsTemp.getGoodsCoverImg());
                    String goodsName = newBeeMallGoodsTemp.getGoodsName();
                    // 字符串过长导致文字超出的问题
                    if (goodsName.length() > 28) {
                        goodsName = goodsName.substring(0, 28) + "...";
                    }
                    newBeeMallShoppingCartItemVO.setGoodsName(goodsName);
                    newBeeMallShoppingCartItemVO.setSellingPrice(newBeeMallGoodsTemp.getSellingPrice());
                    newBeeMallShoppingCartItemVOS.add(newBeeMallShoppingCartItemVO);
                }
            }
        }
        return newBeeMallShoppingCartItemVOS;
    }

    @Override
    public List<NewBeeMallShoppingCartItemVO> getCartItemsForSettle(List<Long> cartItemIds, Long newBeeMallUserId) {
        if (org.springframework.util.CollectionUtils.isEmpty(cartItemIds)) {
            NewBeeMallException.fail("购物项不能为空");
        }
        LambdaQueryWrapper<NewBeeMallShoppingCartItem> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper
                .in(NewBeeMallShoppingCartItem::getCartItemId, cartItemIds)
                .eq(NewBeeMallShoppingCartItem::getUserId, newBeeMallUserId)
                .eq(NewBeeMallShoppingCartItem::getIsDeleted, 0);
        List<NewBeeMallShoppingCartItem> newBeeMallShoppingCartItems = newBeeMallShoppingCartItemMapper.selectList(queryWrapper);
        if (org.springframework.util.CollectionUtils.isEmpty(newBeeMallShoppingCartItems)) {
            NewBeeMallException.fail("购物项不能为空");
        }
        if (newBeeMallShoppingCartItems.size() != cartItemIds.size()) {
            NewBeeMallException.fail("参数异常");
        }
        return getNewBeeMallShoppingCartItemVOS(newBeeMallShoppingCartItems);
    }
}
